#include <stdio.h>
#include <stdbool.h>
#include <string.h>
#include "book.h"
#include <stdlib.h>

bool BorrowBook(P_BookNode_t p, P_Node_t s)
{
    if (p == NULL|| s == NULL)
        return false;
    P_BookNode_t new_node = calloc(1, sizeof(BookNode_t));
    if (new_node == NULL)
    {
        printf("%s,%d:calloc fail\n", __FUNCTION__, __LINE__);
        return false;
    }
    printf("请输入您的姓名：");
    scanf("%s", new_node->data.nameID);
    printf("请输入您的联系方式：");
    scanf("%s", new_node->data.tel);
    printf("请输入所借书籍的书名：");
    scanf("%s", new_node->data.name);
    printf("请输入借书日期（格式xxxx-xx-xx）：");
    scanf("%s", new_node->data.Borrowday);
    
    P_BookNode_t q = p;
    while (q->next != NULL)
    {
        q = q->next;
    }
    q->next = new_node;
    new_node->next = NULL;

    P_Node_t a = s->next;
    while (a != NULL)
    {
        if (strcmp(q->next->data.name, a->data.name) == 0)
        {
            if (a->data.num <= 0)
            {
                printf("库存不足，借书失败！\n");
                free(new_node); // 释放未使用的节点
                return false;
            }
            a->data.num--;
            a->data.count++;
            printf("借书成功！\n");
            return true;
        }

        a = a->next;
    }
    printf("书籍名填写错误或系统没有该图书，借书失败！\n");
    free(new_node); 
    return false;
}